<template>
  <div class="material">
    <el-form ref="ruleFormRef" :model="classRuleForm" label-width="auto" status-icon>
      <el-row>
        <el-col style="margin-right: 10px;" :span="5">
          <el-form-item label="名称" prop="materialName">
            <el-input placeholder="请输入素材名称" v-model.trim="classRuleForm.materialName" />
          </el-form-item>
        </el-col>
        <el-col style="margin-right: 20px;" :span="5">
          <el-form-item label="分类" prop="classification">
            <el-select :empty-values="[null, undefined]" v-model="classRuleForm.classification" placeholder="请选择素材类型">
              <el-option v-for="item in majorOptions" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="goSearch">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>







    <!-- 上传成功之后的显示区域 -->
    <div v-loading="loading">
      <div class="content" v-if="materArr.length">
        <div class="info">
          <div class="left">共{{ materArr.length }}项</div>
        </div>

        <!-- 资料列表 -->

        <el-table :data="materArr" @selection-change="handleSelectionChange"
          style="height: 70vh;  max-width: 100%; overflow-y: auto">
         
          <el-table-column width="500px" label="文件名称" align="left" prop="name" :show-overflow-tooltip="true">
            <template #default="scope">
              <div class="name">
                <div class="icon">
                  <svg class="coloricon" aria-hidden="true">
                    <use :xlink:href="'#' + getFileIcon(scope.row.name)"></use>
                  </svg>
                </div>

                <span>
                  <el-tooltip
        class="box-item"
        effect="dark"
        :content="scope.row.name"
        placement="top"
      >
                  {{ giveEllipsisStr(scope.row.name, 30) }}
                  </el-tooltip>
                </span>

                
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="类型" align="left" prop="t" :show-overflow-tooltip="true">
            <template #default="scope">
              <div class="style">
                <span v-if="scope.row.t == '0'"> <el-tag type="primary">视频</el-tag></span>
                <span v-else-if="scope.row.t == '1'"><el-tag type="success">课件</el-tag></span>
                <span v-else> <el-tag type="warning">资料</el-tag></span>
              </div>
            </template>

          </el-table-column>
          <el-table-column width="200px" label="大小" align="left" prop="size">
            <template #default="scope">
              <div class="size">
                {{ filterSize(scope.row.content_length) }}
              </div>
            </template>

          </el-table-column>
          <el-table-column width="200px" label="创建者" align="left" prop="nick_name">
            <template #default="scope">
              <div class="author">
                {{ scope.row.nick_name }}
              </div>
            </template>

          </el-table-column>

          <el-table-column min-width="321px" label="创建时间" align="left" prop="create_time">
            <template #default="scope">
              <span>
                {{ parseTime(scope.row.create_time) }}
              </span>
            </template>
          </el-table-column>
        </el-table>







      </div>
      <el-empty style=" height: 80vh; display: flex; justify-content: center; align-items: center;"  v-else description="暂无素材" :image-size="200" />
    </div>

    <el-dialog v-model="renameVisible" title="资料重命名" width="500px">
      <el-input v-model.trim="diaIptVal" placeholder="请输入资料名称" clearable size="large" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameVisible = false">取消</el-button>
          <el-button type="primary" @click="reNameEnter">确认修改</el-button>
        </span>
      </template>
    </el-dialog>

   

    <!-- 添加资料的弹出框 -->
    <el-dialog v-model="dialogVisible" width="1100px" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <div class="my-header">
          <h4 v-if="BtnMenuTit == '视频'">上传视频 <span>(仅可上传mp4格式)</span> </h4>
          <h4 v-if="BtnMenuTit == '课件'">上传课件 <span>(仅可上传pdf格式)</span> </h4>
          <h4 v-if="BtnMenuTit == '资料'">上传资料 <span>(仅可上传zip/rar格式)</span> </h4>
        </div>
      </template>

      <MinUpload :fileStyle="fileStyle" ref="minUpload"></MinUpload>



      <template #footer>
        <span class="diaFooter">
          <el-popconfirm title="是否确认取消当前上传任务？" @confirm="resetMater" v-if="store.uploadFileList.length">
            <template #reference>
              <el-button>取消</el-button>
            </template>
          </el-popconfirm>
          <el-button v-else @click="dialogVisible = false">取消</el-button>

          <el-button type="primary" @click="upAddMater" :disabled="bigCfmState">确认上传</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import MinUpload from "@/components/MinUpload.vue";

import useUserStore from "@/store/modules/user";
import {
  downLoadFile,
  filterSize,
  getFileIcon,
  giveEllipsisStr,
  parseTime,
  m3u8Status,
} from "@/utils/common";
import { addMaterialFill, materialList, reNameData, deleteData } from "@/api/material.js";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css";
import "element-plus/es/components/message-box/style/css";

import { Plus,Delete,Search, Refresh } from '@element-plus/icons-vue'
import uploadStore from "@/store/modules/upload";
import counterStore from "@/store/modules/counter";

defineOptions({
  name: "TeachWorksMaterial",
});
const renameHzm = ref("");
const classRuleForm = ref({

  materialName: null,
  classification: '',

})
const majorOptions = ref([
  { label: "全部", value: '' },
  { label: "视频", value: "0" },
  { label: "课件", value: "1" },
  { label: "压缩包", value: "2" }
])
const { proxy } = getCurrentInstance()

const store = uploadStore();
const allChecked = ref(false);
const searchValue = ref("");
const controlState = ref(false);
const dialogVisible = ref(false);
// 素材列表
const materArr = ref([]);


const renameVisible = ref(false);
const diaIptVal = ref();
const outOssid = ref();
const fileId = ref()
const checkedArr = ref([]);
// const bkitem = inject('bkitem')
const bigCfmState = ref(true);
const loading = ref(false);
const BtnMenuTit = ref("");
const fileStyle = ref("")
const btnMenuIdx = ref()
const status = ref(window.sessionStorage.getItem("status"))
const type = ref(null)


// 根据上传的类型返回数字 0视频 1课件  2压缩文件

const fileType = (style) => {
  if (style == ".mp4") {
    return 0
  } else if (style == ".pdf") {
    return 1
  } else {
    return 2
  }
}


//获取资源库资料列表
const getMaterial = (keyname = null, type = null) => {
  loading.value = true;
  let options = {
    bk_id: counterStore().bkItem.id,
    name: keyname,
    t: type,
    page_size: "100",
    page_num: "1"
  }

  materialList(options)
    .then((res) => {


      if (!res.list) {
        ElMessage.error(res.message);
        return;
      }
      materArr.value = res.list;
    })
    .finally(() => {
      loading.value = false;
    });
};

//搜索框搜索
const goSearch = () => {
  if (!classRuleForm.value.classification) {
    getMaterial(classRuleForm.value.materialName, null);
    return
  }
  getMaterial(classRuleForm.value.materialName, classRuleForm.value.classification);
};

//重命名
const goRename = (item) => {

  // 1 记录重命名后缀名
  renameHzm.value = item.name.substr(item.name.lastIndexOf("."));
  // 2，点击重命名的时候去掉后缀名
  diaIptVal.value = item.name.substr(0, item.name.lastIndexOf("."));
  renameVisible.value = true;
  outOssid.value = item.id;
  fileId.value = item.file_id
  type.value = item.t
};
// 点击下载
const goDownLoad = (item) => {
  // item指每一条资料的信息，是一个对象

  // if (item.readOnly) return ElMessage.warning('您没有该权限！')
  downLoadFile(item);
};

//确认修改资料名称
const reNameEnter = () => {
  if (diaIptVal.value.length < 1) {
    ElMessage.error("资料名称的长度不能少于1位")
    return
  }
  if (diaIptVal.value.length > 30) {
    ElMessage.error("资料名称的长度不能超过30位")
    return
  }


  let Options = {
    id: outOssid.value,
    // 3 确认修改拼接后缀名
    name: diaIptVal.value + renameHzm.value,
    file_id: fileId.value,
    bk_id: counterStore().bkItem.id,
    t: type.value
  };


  reNameData(Options).then((res) => {
    ElMessage.success("修改成功");
    renameVisible.value = false;
    getMaterial();
    console.log(res);

    // if (res.code == 200) {
    //   ElMessage.success("修改成功");

    // }
  });
};



const delMetaile = (id) => {
  return deleteData(id)

}
//删除单个资料
const goDel = (item) => {

  let newArr = []
  newArr.push(delMetaile(item.id))
  Promise.all(newArr).then((res) => {
    console.log(res);
    const result = res.some((item) => item.response);
    if (!result) {
      ElMessage.success("删除成功");
      getMaterial()
    } else {
      ElMessage.error("该资料已被使用，无法删除")
      getMaterial()
    }

  })


};


//点击删除多选
const allDelData = async () => {
  //选中多个资料的id数组

  let delarr = checkedArr.value.map((item) => {
    return item.id;
  });

  console.log(delarr);

  let newArr = []
  delarr.forEach(e => {
    newArr.push(delMetaile(e))
  })
  Promise.all(newArr).then((res) => {

    const result = res.some((item) => item.response);
    if (!result) {
      ElMessage.success("删除成功");
      getMaterial()
      controlState.value = false
    } else {
      ElMessage.error("该资料已被使用，无法删除")
      controlState.value = true
      getMaterial()
    }

  })

};






//点击弹出框的取消按钮
const resetMater = () => {
  initUploadFile();
};


//点击确认上传按钮
const upAddMater = () => {
  let addArr = [];
  store.uploadFileList.forEach((item) => {
    if (item.status != "上传成功") {
      return;
    }
    let obj = {
      name: item.name,
      t: fileType(fileStyle.value),
      file_id: item.file_id,
      bk_id: counterStore().bkItem.id
    };
    addArr.push(obj);
  });

  var reqArr = [];
  addArr.forEach((e) => {

    reqArr.push(uploadPush(e));
  });
  Promise.all(reqArr).then((res) => {
    console.log(res);
    ElMessage.success("添加成功");
  });
  initUploadFile();
};

//将上传后的参数传递给数据库
const uploadPush = (addObj) => {
  const loading = ElLoading.service({
    lock: true,
    text: "上传中...",
    background: "rgba(255, 255, 255, 0.7)",
  });

  addMaterialFill(addObj).then((res) => {
    console.log(res);
    if (res) {
      ElMessage.error(res);
      loading.close();
      return;
    }
    if (!res) {
      loading.close();
      dialogVisible.value = false;
      getMaterial();
    }
  });
};

//点击确认或者取消初始化上次数组
const initUploadFile = () => {
  dialogVisible.value = false;
  store.setUploadFileList([]);
};

//监控文件列表是否都上传完成
watch(
  () => store.uploadFileList,
  (nv) => {
    let bool = false;
    if (nv.length) {
      bool = nv.every((item) => {
        return item.status == "上传成功";
      });
    } else {
      bool = false;
    }
    if (bool) {
      bigCfmState.value = false;
    } else {
      bigCfmState.value = true;
    }
  },
  {
    deep: true,
  }
);


// 点击素材按钮下的下拉选项
const onBtnMenu = (item, index) => {
  dialogVisible.value = true
  BtnMenuTit.value = item
  btnMenuIdx.value = index
  if (item == '视频') {
    fileStyle.value = '.mp4'
  } else if (item == '课件') {
    fileStyle.value = '.pdf'
  } else if (item == '资料') {
    fileStyle.value = '.zip,.rar'
  }

}
//获取资料列表
getMaterial();



// 重置表单
const resetForm = () => {
  proxy.$refs.ruleFormRef.resetFields();
  getMaterial();
}

// 表格选中
const handleSelectionChange = (e) => {
  checkedArr.value = e


}
</script>

<style lang="scss" scoped>
.fileDialog {
  .top {
    position: absolute;
    top: 23px;
    left: 120px;
    color: #4395ff;
    cursor: pointer;
  }

  .diacon {
    .item {
      padding: 10px 0;
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      height: 50px;
      align-items: center;

      .left {
        width: 50px;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;

        .coloricon {
          font-size: 40px;
        }
      }

      .rit {
        width: 1000px;
        height: 40px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .text {
          display: flex;
          justify-content: space-between;

          .filename {
            font-size: 16px;
            color: #333;
          }

          .info {
            display: flex;
            color: #999;
            align-items: flex-end;
            font-size: 12px;

            b {
              font-size: 14px;
            }

            .num {
              padding: 0 20px;
            }

            .close {
              width: 22px;
              height: 22px;
              display: flex;
              justify-content: center;
              align-content: center;
              cursor: pointer;

              .iconfont {
                font-size: 22px;
              }
            }

            .close:hover {
              color: #ff5733;
            }
          }
        }

        .line {
          width: 100%;
          height: 3px;
          background: #eee;
          border-radius: 10px;
          position: relative;
          overflow: hidden;

          .progress {
            position: absolute;
            top: 0;
            left: 0;
            width: 33%;
            height: 3px;
            background: #4395ff;
            border-radius: 10px;
          }
        }
      }
    }
  }
}

.content {
  padding: 30px 0;
  .info {
    color: #888;
    font-size: 14px;
    padding-bottom: 15px;
    display: flex;

    b {
      font-weight: 400;
      color: #3485fb;
    }
  }

  .top,
  .row {

    display: flex;
    align-items: center;
  }

  .checked {
    width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .name {
    width: calc(40% - 50px);

    .title {
      width: 40%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;

    }
  }



  .top {
    background: #f5f7fa;
    color: #888;
    line-height: 45px;
    font-size: 14px;
  }




  .name {
    line-height: 55px;
    font-size: 16px;
    color: #555;
    display: flex;
    align-items: center;
    position: relative;

    width: 100%;

    .icon {
      padding-right: 6px;
      display: flex;
      align-items: center;
    }

    .coloricon {
      font-size: 32px;
      margin-right: 4px
    }

    .operate {

      position: absolute;
      top: 0;
      right: 40px;

      display: none;

      ul {
        display: flex;

        li {
          a {
            color: #4395ff;
          }

          padding: 0 10px;
          color: #4395ff;
          font-size: 14px;
          cursor: pointer;
        }

        li:hover,
        li:hover a {
          color: #1a6be6;
        }
      }
    }
  }

  .time {
    font-size: 14px;
    color: #999;
  }


  .el-table tr:hover {
    background: #e7f1ff;

    .operate {
      display: block;
    }
  }
}

.control {
  position: fixed;
  z-index: 105;
  bottom: -80px;
  opacity: 0;
  left: calc(50%);
  width: 190px;
  // height: 45px;
  background: #313136;
  border-radius: 8px;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2);
  transition: 0.5s;

  .item {
    width: 35px;
    height: 35px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    border-radius: 5px;
    margin: 0 3px;

    .iconfont {
      font-size: 25px;
    }
  }

  .item:hover {
    background: #56565a;
  }
}

.control.active {
  bottom: 80px;
  opacity: 1;

}

.btnGroup{

  display: flex;
  margin-top: 20px;

}

.commBtn {
  width: 110px;
  position: relative;
  margin-right: 15px;

  &:hover {
    .btnMenu {
      display: block;
    }
  }

  .btnMenu {
    width: 80%;

    background: #fff;
    border-radius: 5px;
    z-index: 4;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    position: absolute;
    top: 32px;
    left: 10px;
    display: none;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    cursor: pointer;

    p {
      padding: 10px 0;
      width: 100%;
      text-align: center;
      font-size: 14px;
    }
  }
}

.my-header {
  h4 {
    font-weight: 400;
    font-size: 18px;
    color: #333;

    span {
      color: red !important;
    }
  }
}
</style>
